<?php

namespace App\Models\Goods;
use App\Models\BaseModel;
use App\Params\Backend\CategoryListParams;
use App\Params\Backend\CategoryUpdateParam;
use Illuminate\Database\Eloquent\Model;

/**
 * 商品分类模型类
 *
 * @author WangBin
 * @date 2021-09-24
 * @package App\Http\Models
 */
class Category extends BaseModel
{
    protected $table = 'b2c_goods_category';
    protected $primaryKey = 'category_id';

    /**
     * 获取子分类个数
     *
     * @param int $categoryId
     * @return int
     */
    public static function getChildCount(int $categoryId)
    {
        return Category::query()->where('parent_id', $categoryId)->where('is_active', 1)->count();
    }

    /**
     * 根据层级获取分类
     *
     * @param int $level
     * @return
     */
    public static function getChild(int $level)
    {
        return Category::query()->where('level', $level -1)->where('is_active', 1)->get();
    }

    /**
     * 根据ID获取分类
     *
     * @param int $id
     * @return \Illuminate\Database\Eloquent\Builder|Model|object|null
     */
    public static function getById(int $id)
    {
        return Category::query()->where('category_id', $id)->first();
    }

    /**
     * 获取分类列表
     *
     * @param CategoryListParams $filter
     * @return \Illuminate\Database\Eloquent\Builder
     */
    public static function getByFilter(CategoryListParams $filter)
    {
        $category = Category::query();
        if($filter->getName()) {
            $category->where('name', 'like', '%' . $filter->getName() . '%');
        }
        if($filter->getParentId()) {
            $category->where('parent_id', $filter->getParentId());
        }
        $category = $category->orderByDesc('created_at');
        return $category;
    }

    /**
     * 保存分类
     *
     * @param CategoryUpdateParam $data
     * @return int
     */
    public static function saveData(CategoryUpdateParam $data)
    {
        $category = $data->getCategoryId() ? Category::find($data->getCategoryId()) : new Category();
        unset($data->category_id);
        foreach ($data as $field => $val)
        {
            $category->{$field} = $val;
        }
        return $category->save() ? $category->category_id : 0;
    }

    /**
     * 更新数据
     *
     * @param int $categoryId
     * @param array $data
     * @return int
     */
    public static function updateData(int $categoryId, array $data)
    {
        return Category::query()->where('category_id', $categoryId)->update($data);
    }

    /**
     * 停用/启用分类
     *
     * @param int $categoryId
     * @param int $isActive
     * @return int
     */
    public static function enable(int $categoryId, int $isActive)
    {
        return Category::query()->where('category_id', $categoryId)->update(['is_active' => $isActive]);
    }
}
